package com.njdf.servlet;

import com.njdf.entity.People;
import com.njdf.service.UserService;
import com.njdf.service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        String name1 = request.getParameter("uname");
        String pwd1 = request.getParameter("upwd");
        String upwd2 = request.getParameter("upwd2");
        PrintWriter out = response.getWriter();
        if (pwd1 != "" && pwd1 != null && upwd2 != "" && upwd2 != null) {
            if (pwd1.equals(upwd2)) {
                People people = new People(name1, pwd1, upwd2);
                UserService userService = new UserServiceImpl();
                Boolean b = userService.update(people);
                if (b) {
                    List<People> peoples=new ArrayList<>();
//                    people=userService.queryByName(name1);
                    peoples= userService.queryAll();
                    request.setAttribute("peoples",peoples);
//                    request.getSession().setAttribute("people",people);
                    request.getRequestDispatcher("/success.jsp").forward(request, response);
                } else {
                    out.print("<script>alert('更新失败');window.history.go(-1);</script>");
                }
            } else {
                out.print("<script>alert('两次密码不一致');window.history.go(-1);</script>");
            }
        }else if(pwd1==""||pwd1==null){
                out.print("<script>alert('密码不能为空');window.history.go(-1);</script>");
//                request.getRequestDispatcher("update.jsp?name="+name1+"&password="+upwd2+"&password2="+upwd2).forward(request,response);
//            response.setHeader("refresh", "2;update.jsp?name="+name1+"&password="+pwd1+"&password2="+pwd1);
//            response.addHeader("refresh", "2;update.jsp?name="+name1+"&password="+pwd1+"&password2="+pwd1);

        }else {
            out.print("<script>alert('确认密码不能为空');window.history.go(-1);</script>");
//            response.setHeader("refresh", "2;update.jsp?name="+name1+"&password="+pwd1+"&password2="+pwd1);
//            request.getRequestDispatcher("update.jsp?name="+name1+"&password="+pwd1+"&password2="+pwd1).forward(request,response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
